<template>
  <div class="bgc-white" style="display: flex; width: 100%; height: calc(100vh - 112px); overflow: hidden">
    <div class="leftBox">
      <div style="display: flex; justify-content: space-between; align-items: center">
        <div class="fs16 fw500" style="color: #252525">供应商分组</div>
        <a-button style="padding: 0" type="link" @click="showAddGroup">
          <a-icon type="plus" style="color: #000000" />
        </a-button>
      </div>
      <a-input-search v-model="groupNameQuery" placeholder="搜索分组" class="mt12" style="width: 252px" allow-clear @search="onSearch" />
      <div v-if="groupList" class="mt12">
        <a-tree :treeData="groupList" :defaultExpandAll="true" :selectedKeys="[currentGroup.value]" class="tree-control">
          <template slot="custom" slot-scope="item">
            <div style="display: flex; justify-content: space-between; align-items: center" @click="onGroupClick(item)">
              <a-tooltip :title="`${item.title}（${item.count || 0}）`">
                <div class="item-text">{{ item.title }}（{{ item.count || 0 }}）</div>
              </a-tooltip>
              <div v-if="item.type !== 'site'" class="ta-right" style="width: 40px" @click.stop="showEditGroup(item)">
                <a-icon type="setting" theme="filled" />
              </div>
            </div>
          </template>
        </a-tree>
      </div>
    </div>
    <a-spin v-if="columns" :spinning="spinning" class="p24" style="width: calc(100% - 300px)">
      <div class="p24 mb24" style="border: 1px solid rgba(217, 217, 217, 1); border-radius: 4px">
        <div class="fs18 fw500" style="color: rgba(60, 61, 67, 1)">{{ this.currentGroup ? this.currentGroup.title : "" }}</div>
        <div v-if="this.currentGroup && this.currentGroup.desc" class="mt16 fs12" style="color: rgba(166, 168, 180, 1)">
          {{ this.currentGroup ? this.currentGroup.desc : "" }}
        </div>
      </div>
      <TableTitle style="padding: 0; height: 32px; line-height: 32px; margin: 4px 0 16px">
        <template slot="title"></template>
        <template slot="action">
          <a-tooltip v-if="dropdownDisabled" title="请先选中供应商分组再新增供应商">
            <a-icon type="question-circle" theme="filled" class="mr12" style="color: #d9d9d9; font-size: 16px" />
          </a-tooltip>
          <a-dropdown :disabled="dropdownDisabled">
            <a-menu slot="overlay">
              <a-menu-item @click="goDetail('add')">手动添加</a-menu-item>
              <a-menu-item @click="genQrcode">链接邀请</a-menu-item>
            </a-menu>
            <a-button type="primary">新增供应商</a-button>
          </a-dropdown>
        </template>
      </TableTitle>
      <TableBody
        selectHead
        selection
        tableName="gys"
        tableHeadUrl="/hr/api/v1/formGroups/getHead"
        :hasAddition="true"
        :selectedHead.sync="selectedHead"
        :selectedRowKeys.sync="selectedRowKeys"
        :source="gysList"
        headerRowID="sortable_list"
        :columns="columns"
        :subjectId="siteId"
        subjectType="site"
        class="mt12 gys-tb"
        @onClose="() => {}"
        @onSearch="selectFunc()"
        @onReload="selectFunc()"
        @headLoaded="onHeadLoaded"
      >
        <template slot="search">
          <a-input-search
            v-model="searchKey"
            :allowClear="true"
            placeholder="搜索名称/联系电话/联系人"
            style="width: 300px"
            @search="searchGys"
          />
        </template>
        <template slot="export">
          <a-divider type="vertical" />
          <a-button class="action-btn" type="link" @click="exportExcel">导出全部 <a-icon type="download" /></a-button>
        </template>
        <template slot-scope="prop">
          <a-table
            :class="prop.className"
            :components="prop.components"
            :columns="prop.columns"
            :scroll="{ x: prop.scrollWidth, y: scrollHeight }"
            :customHeaderRow="
              () => {
                return {
                  domProps: {
                    id: prop.headerRowID
                  }
                };
              }
            "
            :data-source="gysList"
            row-key="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange
            }"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <template v-for="col in prop.columns" #[col.dataIndex]="text, record">
              <span v-if="col.dataIndex === 'action'" :key="col.dataIndex" class="table-action">
                <a-space style="display: flex; align-items: center; width: 80px">
                  <a @click="goDetail('edit', record.id)">详情</a>
                  <a-popconfirm title="确认要删除记录吗？" okText="确认" cancelText="取消" @confirm="deleteGys(record)">
                    <a>删除</a>
                  </a-popconfirm>
                </a-space>
              </span>
              <a-tooltip
                v-else-if="columnMap[col.dataIndex]"
                :key="col.dataIndex"
                :title="formatColumnItem(columnMap[col.dataIndex], text)"
              >
                <span>
                  {{ formatColumnItem(columnMap[col.dataIndex], text) }}
                </span>
              </a-tooltip>
              <span v-else :key="col.dataIndex">{{ text }}</span>
            </template>
          </a-table>
        </template>
      </TableBody>
    </a-spin>
    <a-drawer :width="450" :title="groupTitle" placement="right" :visible="groupVisible" @close="onGroupClose">
      <div>
        <div style="display: flex; justify-content: center; align-items: center">
          <div style="color: #fa5051; margin-right: 4px">*</div>
          <div style="font-size: 14px; font-weight: 400; color: #55565d">上级分组</div>
          <a-tree-select
            v-model="groupParentId"
            :treeData="groupList"
            placeholder="请选择上级分组"
            style="width: 248px; margin-left: 10px"
            @select="onGroupParentSelect"
          />
        </div>
        <div class="mt24" style="display: flex; justify-content: center; align-items: center">
          <div style="color: #fa5051; margin-right: 4px">*</div>
          <div style="font-size: 14px; font-weight: 400; color: #55565d">分组名称</div>
          <a-input v-model="groupName" placeholder="请输入分组名称" style="width: 248px; margin-left: 10px"></a-input>
        </div>
        <div class="mt24" style="display: flex; justify-content: center; align-items: flex-start">
          <div style="font-size: 14px; font-weight: 400; color: #55565d; margin-left: 9px">分组说明</div>
          <a-textarea
            v-model="groupDescribe"
            :maxLength="150"
            placeholder="最多150个字"
            style="width: 248px; margin-left: 10px; min-height: 120px"
          />
        </div>
      </div>
      <a-space
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
          display: 'flex',
          justifyContent: 'center'
        }"
      >
        <a-button
          v-if="groupTitle === '编辑分组'"
          :style="{
            color: '#FA5051',
            borderColor: '#FA5051'
          }"
          @click="deleteGroup"
        >
          删除
        </a-button>
        <a-button @click="onGroupClose"> 取消 </a-button>
        <a-button type="primary" @click="addGroupOk"> 确定 </a-button>
      </a-space>
    </a-drawer>
    <a-modal v-model="qrcodeVisible" destroyOnClose title="登记二维码">
      <div id="qrbox" style="width: 200px; height: 200px; margin: 0 auto"></div>
      <div class="mt24 ta-center">
        <a-button @click="saveQrcode">下载</a-button>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { groupListReq, groupCreateReq, groupUpdateReq, groupDeleteReq } from "./api";
import { findFormGysReq } from "./api";
import { gysListReq, gysDeleteReq, gysExportReq } from "./api";
import { tableValueAreaDetail, tableValueArea } from "./funcs";
import QRCode from "qrcodejs2";
import html2canvas from "html2canvas";
import { mapState } from "vuex";
export default {
  name: "",
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      groupVisible: false,
      groupTitle: "",
      groupName: "",
      groupDescribe: "",
      groupId: "",
      groupNameQuery: "",
      groupList: null,
      groupParentId: undefined,
      groupParentLevel: "",
      currentGroup: null,
      selectedHead: [],
      selectedRowKeys: [],
      gysList: [],
      columns: null,
      searchKey: null,
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      spinning: false,
      columnMap: null,
      qrcodeVisible: false
    };
  },
  computed: {
    ...mapState(["auth", "app"]),
    siteId() {
      return this.auth.siteId;
    },
    dropdownDisabled() {
      return this.currentGroup && this.currentGroup.type === "site";
    },
    scrollHeight() {
      return this.app.mainHeight - 460;
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.buildInitColumns();
  },
  methods: {
    formatColumnItem(item, text) {
      if (item.fieldType === 9) {
        return tableValueAreaDetail(text);
      } else if (item.fieldType === 6) {
        return tableValueArea(text);
      } else {
        return text;
      }
    },
    exportExcel() {
      gysExportReq({
        searchKey: this.searchKey,
        groupId: this.currentGroup.type === "site" ? null : this.currentGroup.value
      })
        .then((res) => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.download = "全部供应商.xlsx";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("error log --> ", err);
          this.spinning = false;
        });
    },
    onHeadLoaded() {
      this.loadGroup();
    },
    genQrcode() {
      this.qrcodeVisible = true;
      this.$nextTick(() => {
        new QRCode("qrbox", {
          width: 200,
          height: 200, // 高度
          text: `${location.origin}/back/#/gys_reg?mode=add&groupId=${this.currentGroup.value}&siteId=${this.$store.state.auth.siteId}` // 二维码内容
        });
      });
    },
    // 下载
    saveQrcode() {
      html2canvas(document.getElementById("qrbox"), {
        useCORS: true,
        allowTaint: false
      })
        .then((canvas) => {
          const MIME_TYPE = "image/png";
          const imgURL = canvas.toDataURL("image/png");
          const link = document.createElement("a");
          link.download = `登记二维码`;
          link.href = imgURL;
          link.dataset.downloadurl = [MIME_TYPE, link.download, link.href].join(":");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          this.qrcodeVisible = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    deleteGys(item) {
      gysDeleteReq(item.id)
        .then((res) => {
          this.$message.success("删除成功");
          this.loadList();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    goDetail(mode, gysId) {
      if (mode === "add") {
        sessionStorage.setItem("currentGroupForAdd", this.currentGroup.value);
      }
      this.$router.push({
        path: "/admin/supplier/detail",
        query: { mode, groupId: this.currentGroup.value, gysId }
      });
    },
    buildInitColumns() {
      findFormGysReq()
        .then((res) => {
          const arr1 = [];
          for (let i = 0; i < res.data.length; i++) {
            const li1 = res.data[i];
            for (let j = 0; j < li1.formGroupFieldList.length; j++) {
              const li2 = li1.formGroupFieldList[j];
              arr1.push(li2);
            }
          }
          const arr2 = [];
          const map = {};
          for (let i = 0; i < arr1.length; i++) {
            const item = arr1[i];
            const dataIndex = item.fieldCode || "" + item.id;
            const itemNew = {
              title: item.fieldName,
              dataIndex,
              fieldType: item.fieldType,
              ellipsis: true,
              scopedSlots: {
                customRender: `${dataIndex}`
              }
            };
            // arr2.push(itemNew);
            map[`${dataIndex}`] = itemNew;
          }
          arr2.push({
            title: "操作",
            dataIndex: "action",
            width: "96px",
            align: "center",
            fixed: "right",
            scopedSlots: {
              customRender: "action"
            }
          });
          this.columnMap = map;
          this.columns = arr2;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    selectFunc() {
      this.pagination.current = 1;
      this.selectedRowKeys = [];
      this.loadList();
    },
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.loadList();
    },
    onSelectChange(selectedRowKeys, tList) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRowList = tList;
    },
    searchGys() {
      this.pagination.current = 1;
      this.loadList();
    },
    loadList() {
      this.spinning = true;
      const params = {
        searchKey: this.searchKey,
        groupId: this.currentGroup.type === "site" ? null : this.currentGroup.value,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      gysListReq(params)
        .then((res) => {
          this.gysList = res.data.entities;
          this.pagination.total = res.data.entityCount;
          this.spinning = false;
        })
        .catch((err) => {
          this.spinning = false;
          console.log(err);
        });
    },
    onGroupClick(item) {
      if (!this.currentGroup || item.value !== this.currentGroup.value) {
        this.currentGroup = item;
        this.pagination.current = 1;
        this.loadList();
      }
    },
    onGroupParentSelect(value, node) {
      this.groupParentId = value;
      this.groupParentLevel = node.dataRef.level;
    },
    loadGroup() {
      groupListReq({
        groupName: this.groupNameQuery
      }).then((res) => {
        const currentGroupForAddId = sessionStorage.getItem("currentGroupForAdd");
        this.groupList = formatTreeData(res.data, currentGroupForAddId);
        if (!this.currentGroup) {
          try {
            const currentGroupSession = sessionStorage.getItem("currentGroup");
            if (currentGroupSession) {
              this.onGroupClick(JSON.parse(currentGroupSession));
              sessionStorage.removeItem("currentGroupForAdd");
              sessionStorage.removeItem("currentGroup");
            } else {
              this.onGroupClick(this.groupList[0]);
            }
          } catch (err) {
            this.onGroupClick(this.groupList[0]);
          }
        }
      });
    },
    onSearch() {
      this.loadGroup();
    },
    onGroupClose() {
      this.groupVisible = false;
    },
    showAddGroup() {
      this.groupVisible = true;
      this.groupTitle = "添加分组";
      this.groupName = undefined;
      this.groupDescribe = undefined;
      this.groupParentId = this.currentGroup.value;
      this.groupParentLevel = this.currentGroup.level;
    },
    showEditGroup(item) {
      this.groupVisible = true;
      this.groupTitle = "编辑分组";
      this.groupName = item.title;
      this.groupDescribe = item.desc;
      this.groupId = item.value;
      this.groupParentId = item.parentId;
      this.groupParentLevel = item.level - 1;
    },
    addGroupOk() {
      if (!this.groupName) {
        this.$message.warning("分组名称必填！");
      } else {
        if (this.groupTitle === "添加分组") {
          groupCreateReq({
            groupType: "ordinary",
            sort: 1,
            name: this.groupName,
            groupDesc: this.groupDescribe,
            parentId: this.groupParentId,
            level: this.groupParentLevel + 1
          })
            .then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "新增成功"
              });
              this.loadGroup();
              this.groupVisible = false;
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        } else if (this.groupTitle === "编辑分组") {
          groupUpdateReq({
            name: this.groupName,
            groupDesc: this.groupDescribe,
            groupType: "ordinary",
            sort: 1,
            parentId: this.groupParentId,
            level: this.groupParentLevel + 1,
            id: this.groupId
          })
            .then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "编辑成功"
              });
              this.loadGroup();
              this.groupVisible = false;
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        }
      }
    },
    deleteGroup() {
      groupDeleteReq(this.groupId)
        .then((res) => {
          this.$notification["success"]({
            message: "success",
            description: "删除成功"
          });
          this.loadGroup();
          this.groupVisible = false;
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    }
  }
};

function formatTreeData(list, currentGroupForAddId) {
  const temp = [];
  list.forEach((item) => {
    const itemTemp = {
      title: item.name,
      key: item.id,
      value: item.id,
      type: item.groupType,
      desc: item.groupDesc,
      level: item.level,
      parentId: item.parentId,
      count: item.gysCount,
      children: item.childList ? formatTreeData(item.childList, currentGroupForAddId) : [],
      scopedSlots: { title: "custom" }
    };
    if (currentGroupForAddId && currentGroupForAddId === item.id) {
      sessionStorage.setItem("currentGroup", JSON.stringify(itemTemp));
    }
    temp.push(itemTemp);
  });
  return temp;
}
</script>
<style lang="scss" scoped>
.gys-tb {
  ::v-deep .table-body-top-search {
    margin-top: -48px;
  }
}
.leftBox {
  width: 300px;
  overflow-x: auto;
  border-right: 1px solid #e8e8e8;
  min-height: 490px;
  padding: 12px 24px;
  flex-shrink: 0;
  .itemHover:hover {
    color: var(--primary);
    background: var(--primary10);
  }
  .itemHoverIng {
    color: var(--primary);
    background: var(--primary10);
  }
}
.rightBox {
  width: 100%;
  padding: 24px;
  .titleBox {
    width: 100%;
    height: 96px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 24px;
  }
}
.tree-control {
  height: 100%;
  ::v-deep .ant-tree-switcher {
    height: 40px;
    line-height: 40px;
    display: none;
  }
  ::v-deep .ant-tree-node-content-wrapper {
    height: 40px;
    line-height: 40px;
    width: 100%;
    max-width: 251px;
    min-width: 160px;
    &.ant-tree-node-selected {
      background: var(--primary10);
      .anticon {
        color: var(--primary);
      }
    }
  }
  .item-text {
    max-width: 211px;
    overflow-x: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
